package de.sky.mathparser.parser.parser;

import java.text.ParseException;
import java.util.List;

import de.sky.mathparser.parser.syntaxtree.AbstractSyntaxTree;
import de.sky.mathparser.parser.token.Token;
import de.sky.mathparser.parser.token.TokenType;

public class Parser {

	public AbstractSyntaxTree parse(List<Token> tokens) throws ParseException {
		AbstractSyntaxTree overallTree = new AbstractSyntaxTree();

		AbstractSyntaxTree currentTree = overallTree;
		int parameterCounter = 0;
		for (Token tok : tokens) {
			if (tok.isToken(TokenType.LEFT_PARENTHESIS)) {
				currentTree = currentTree.openBranch();
				parameterCounter = 0;
			} else if (tok.isToken(TokenType.RIGHT_PARENTHESIS)) {
				currentTree = currentTree.closeBranch();
			} else if (tok.isToken(TokenType.OPERATOR)) {
				currentTree.add(tok.getOperator());
			} else if (tok.isToken(TokenType.NUMBER)) {
				currentTree.add(parameterCounter++, tok.getNumber());
			}
		}

		return overallTree;
	}

}
